package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.utils.*;
import com.ruoyi.packages.domain.PackageStorage;
import com.ruoyi.packages.service.IPackageStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.ShiroConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 首页 业务处理
 * 
 * @author ruoyi
 */
@Controller
public class SysIndexController extends BaseController
{
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private IPackageStorageService packageStorageService;

    // 系统首页
    @GetMapping("/index")
        public String index(ModelMap mmap)
    {
        // 取身份信息
        SysUser user = ShiroUtils.getSysUser();
        // 根据用户id取出菜单
        List<SysMenu> menus = menuService.selectMenusByUser(user);
        mmap.put("menus", menus);
        mmap.put("user", user);
        mmap.put("sideTheme", configService.selectConfigByKey("sys.index.sideTheme"));
        mmap.put("skinName", configService.selectConfigByKey("sys.index.skinName"));
        mmap.put("ignoreFooter", configService.selectConfigByKey("sys.index.ignoreFooter"));
        mmap.put("copyrightYear", RuoYiConfig.getCopyrightYear());
        mmap.put("demoEnabled", RuoYiConfig.isDemoEnabled());
        mmap.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        mmap.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));

        // 菜单导航显示风格
        String menuStyle = configService.selectConfigByKey("sys.index.menuStyle");
        // 移动端，默认使左侧导航菜单，否则取默认配置
        String indexStyle = ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")) ? "index" : menuStyle;

        // 优先Cookie配置导航菜单
        Cookie[] cookies = ServletUtils.getRequest().getCookies();
        for (Cookie cookie : cookies)
        {
            if (StringUtils.isNotEmpty(cookie.getName()) && "nav-style".equalsIgnoreCase(cookie.getName()))
            {
                indexStyle = cookie.getValue();
                break;
            }
        }
        String webIndex = "topnav".equalsIgnoreCase(indexStyle) ? "index-topnav" : "index";
        return webIndex;
    }

    // 锁定屏幕
    @GetMapping("/lockscreen")
    public String lockscreen(ModelMap mmap)
    {
        mmap.put("user", ShiroUtils.getSysUser());
        ServletUtils.getSession().setAttribute(ShiroConstants.LOCK_SCREEN, true);
        return "lock";
    }

    // 解锁屏幕
    @PostMapping("/unlockscreen")
    @ResponseBody
    public AjaxResult unlockscreen(String password)
    {
        SysUser user = ShiroUtils.getSysUser();
        if (StringUtils.isNull(user))
        {
            return AjaxResult.error("服务器超时，请重新登陆");
        }
        if (passwordService.matches(user, password))
        {
            ServletUtils.getSession().removeAttribute(ShiroConstants.LOCK_SCREEN);
            return AjaxResult.success();
        }
        return AjaxResult.error("密码不正确，请重新输入。");
    }

    // 切换主题
    @GetMapping("/system/switchSkin")
    public String switchSkin()
    {
        return "skin";
    }

    // 切换菜单
    @GetMapping("/system/menuStyle/{style}")
    public void menuStyle(@PathVariable String style, HttpServletResponse response)
    {
        CookieUtils.setCookie(response, "nav-style", style);
    }

    // 系统介绍
    @GetMapping("/system/main")
    public String main(ModelMap mmap)
    {
        mmap.put("version", RuoYiConfig.getVersion());
        //查询数据
        //暂且根据部门排序方式来
        String orderNum = ShiroUtils.getSysUser().getDept().getOrderNum();
        PackageStorage packageStorage = new PackageStorage();
        PackageStorage packageStorage1 = new PackageStorage();
        //地方仓
        if(Integer.valueOf(orderNum)>=5){
            //今天的日期
            String today= DateUtil.today();
            //昨天
            DateTime yesterday = DateUtil.yesterday();
            String ys = DateUtils.dateTime(yesterday);
            //前天
            DateTime newDate2 = DateUtil.offsetDay(new Date(), -2);
            String bys = DateUtils.dateTime(newDate2);


            packageStorage.setSendAreaId(Long.valueOf(orderNum));
            Integer receive= packageStorageService.selectPackageStorageForStatistics(packageStorage,"receive");
            Integer day_receive= packageStorageService.selectPackageStorageForDayStatistics(packageStorage,"receive");
            Integer ys_receive= packageStorageService.selectPackageStorageForYesterdayStatistics(packageStorage,"receive");
            Integer bys_receive= packageStorageService.selectPackageStorageForBeforeYesterdayStatistics(packageStorage,"receive");
            packageStorage.setReceiveTime(null);

            Integer send= packageStorageService.selectPackageStorageForStatistics(packageStorage,"send");
            Integer day_send= packageStorageService.selectPackageStorageForDayStatistics(packageStorage,"send");
            Integer ys_send= packageStorageService.selectPackageStorageForYesterdayStatistics(packageStorage,"send");
            Integer bys_send= packageStorageService.selectPackageStorageForBeforeYesterdayStatistics(packageStorage,"send");
            packageStorage.setSendTime(null);

            Integer sign= packageStorageService.selectPackageStorageForStatistics(packageStorage,"sign");
            Integer day_sign= packageStorageService.selectPackageStorageForDayStatistics(packageStorage,"sign");
            Integer ys_sign= packageStorageService.selectPackageStorageForYesterdayStatistics(packageStorage,"sign");
            Integer bys_sign= packageStorageService.selectPackageStorageForBeforeYesterdayStatistics(packageStorage,"sign");
            packageStorage.setSignTime(null);

            //查询待入库信息
            String dictValue = DictUtils.getDictValue("package_status", "发往地方仓库");
            packageStorage1.setSendAreaId(Long.valueOf(orderNum));
            packageStorage1.setStatus(Long.valueOf(dictValue));
            Integer load= packageStorageService.selectPackageStorageForStatistics(packageStorage1,"out");
            Integer day_load= packageStorageService.selectPackageStorageForDayStatistics(packageStorage1,"out");
            Integer ys_load= packageStorageService.selectPackageStorageForYesterdayStatistics(packageStorage1,"out");
            Integer bys_load= packageStorageService.selectPackageStorageForBeforeYesterdayStatistics(packageStorage1,"out");

            if(ShiroUtils.getSysUser().getRoles().get(0).getRoleName().equals("快递员")){
                //查询快递员
                PackageStorage packageStorage2 = new PackageStorage();
                String dictValue1 = DictUtils.getDictValue("package_status", "派件中");
                packageStorage2.setExpressman(String.valueOf(ShiroUtils.getUserId()));
                packageStorage2.setStatus(Long.valueOf(dictValue1));
                packageStorage2.setSendAreaId(Long.valueOf(orderNum));
                Integer sendNum= packageStorageService.selectPackageStorageForStatistics(packageStorage2,"send");
                packageStorage2.setSendTime(null);

                String dictValue2 = DictUtils.getDictValue("package_status", "收件人已签收");
//                packageStorage2.setSignBy(String.valueOf(ShiroUtils.getUserId()));
                packageStorage2.setStatus(Long.valueOf(dictValue2));
                Integer signTotalNum= packageStorageService.selectPackageStorageForStatistics(packageStorage2,"sign");
                Integer daySignTotalNum= packageStorageService.selectPackageStorageForDayStatistics(packageStorage2,"sign");
                Integer monthSignTotalNum= packageStorageService.selectPackageStorageForMonthStatistics(packageStorage2,"sign");


                mmap.put("express_send_num",sendNum);
                mmap.put("express_sign_total_num",signTotalNum);
                mmap.put("express_sign_day_total_num",daySignTotalNum);
                mmap.put("express_sign_month_total_num",monthSignTotalNum);
            }

            mmap.put("load_num",load);
            mmap.put("day_load_num",today+"从国内仓出库数量："+day_load);
            mmap.put("ys_load_num",ys+"从国内仓出库数量："+ys_load);
            mmap.put("bys_load_num",bys+"从国内仓出库数量："+bys_load);

            mmap.put("in_num",receive);
            mmap.put("day_in_num",today+"入库数量："+day_receive);
            mmap.put("ys_in_num",ys+"入库数量："+ys_receive);
            mmap.put("bys_in_num",bys+"入库数量："+bys_receive);

            mmap.put("out_num",send);
            mmap.put("day_out_num",today+"出库数量："+day_send);
            mmap.put("ys_out_num",ys+"出库数量："+ys_send);
            mmap.put("bys_out_num",bys+"出库数量："+bys_send);

            mmap.put("sign_num",sign);
            mmap.put("day_sign_num",today+"签收数量："+day_sign);
            mmap.put("ys_sign_num",ys+"签收数量："+ys_sign);
            mmap.put("bys_sign_num",bys+"签收数量："+bys_sign);






        }else if(Integer.valueOf(orderNum)>0){
            Integer create= packageStorageService.selectPackageStorageForStatistics(packageStorage,"create");
            packageStorage.setCreateTime(null);
            Integer out= packageStorageService.selectPackageStorageForStatistics(packageStorage,"out");
            packageStorage.setOutTime(null);
            mmap.put("in_num",create);
            mmap.put("out_num",out);
        }


        return "main";
    }

    // 检查初始密码是否提醒修改
    public boolean initPasswordIsModify(Date pwdUpdateDate)
    {
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    // 检查密码是否过期
    public boolean passwordIsExpiration(Date pwdUpdateDate)
    {
        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
        if (passwordValidateDays != null && passwordValidateDays > 0)
        {
            if (StringUtils.isNull(pwdUpdateDate))
            {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }
}
